import json

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from django_redis import get_redis_connection

from worker import celery_app

ACCESS_KEY_ID = "LTAI4FixbMkEtHNLQ6P1X8Ad"  # ⽤户AccessKey  需要根据⾃⼰的账户修改
ACCESS_KEY_SECRET = "igOwY3j9kzll6pNNLjHRwDlsDqZSWp"  # Access Key Secret  需要根据⾃⼰的账户修改
client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, 'cn-hangzhou')


@celery_app.task
def send_sms(phone, vcode):
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', "cn-hangzhou")
    request.add_query_param('PhoneNumbers', phone)
    request.add_query_param('SignName', '风中一匹狼')
    request.add_query_param('TemplateCode', 'SMS_184830502')
    para = "{'code':'%s'}" % vcode
    redis = get_redis_connection("sms_code")
    SMS_EXPIRE_TIME = 3600
    redis.hmset('sms_%s' % phone, {'phone': phone, 'para': vcode})
    redis.expire('sms_%s' % phone, SMS_EXPIRE_TIME)
    request.add_query_param('TemplateParam', para)
    response = client.do_action_with_exception(request)
    result = json.loads(response, encoding='utf-8')
    code = result.get('Code')
    if code == 'OK':
        return True
    return False
